import { AddressTag, Sex } from '@/constants/commonConst';
import {
  getTakeAwayUserAddressById,
  getTakeAwayUserAddressAll,
  getTakeAwayUserAddressPageList,
  commonUpdate,
  updateTakeAwayUserAddress,
  addTakeAwayUserAddress,
  deleteTakeAwayUserAddress
} from '@/services/takeAwayUserAddressService';
import { dateFormat } from '@/utils/common';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';

/**
 *
 * @constructor
 */
const TakeAwayUserAddressPage: React.FC<unknown> = () => {
  const [updateData, setUpdateData] = useState<TakeAwayUserAddressType.TakeAwayUserAddress>(
    {} as TakeAwayUserAddressType.TakeAwayUserAddress,
  );
  const actionRef = useRef<ActionType>();

  /**
   *
   * @param
   */
  const doDelete = async (model: TakeAwayUserAddressType.TakeAwayUserAddress) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteTakeAwayUserAddress({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  /**
   *
   */
  const columns: ProColumns<TakeAwayUserAddressType.TakeAwayUserAddressResponse>[] = [
    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true
    },
    {
      title: '收货人',
      dataIndex: 'UserId',
      renderText(text, record) {
        return record.Receiver;
      },
    },
    {
      title: '收货地址',
      dataIndex: 'Address',
      hideInSearch: true,
      renderText(text, record) {
        return record.Address + record.HouseNumber;
      },
    },
    {
      title: '经度',
      dataIndex: 'Lng',
      hideInSearch: true
    },
    {
      title: '纬度',
      dataIndex: 'Lat',
      hideInSearch: true
    },
    {
      title: '手机号',
      dataIndex: 'PhoneNumber'
    },
    {
      title: '是否默认地址',
      dataIndex: 'IsDefault',
      hideInSearch: true,
      render(text, record) {
        return record.IsDefault ? <input type='checkbox' defaultChecked /> : <input type='checkbox' />;
      },
    },

    {
      title: '标签',
      dataIndex: 'Tag',
      renderText(text, record) {
        const currentSex = AddressTag.find(r => r.value == record.Tag);
        return currentSex?.label;
      },
    },

    {
      title: '新增时间',
      dataIndex: 'AddTime',
      hideInSearch: true,
      renderText(text, record) {
        return dateFormat(record.AddTime, 'yyyy-mm-dd hh:mm:ss');
      },
    },
    {
      title: '修改时间',
      dataIndex: 'UpdateTime',
      hideInSearch: true,
      renderText(text, record) {
        return dateFormat(record.UpdateTime, 'yyyy-mm-dd hh:mm:ss');
      },
    },

    {
      title: '性别',
      dataIndex: 'Sex',
      hideInSearch: true,
      renderText(text, record) {
        const currentSex = Sex.find(r => r.value == record.Sex);
        return currentSex?.label;
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <Space split={<Divider type="vertical" />}>
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TakeAwayUserAddressType.TakeAwayUserAddressResponse>
        headerTitle="管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
        ]}
        request={async (params: any, sorter: any) => {
          const searchParams: PageInfo.PageRequest = {
            pageSize: params.pageSize,
            current: params.current
          };

          let sortQuery = "", filterQuery = "";
          // eslint-disable-next-line guard-for-in
          for (const key in sorter) {
            sortQuery += `${key}|${sorter[key]}`;
          }

          if (sortQuery != "") {
            searchParams['@sort'] = sortQuery;
          }

          for (const key in params) {
            if (key !== "pageSize" && key !== "current") {
              if (params[key] != "") {
                filterQuery += `contains(${key},${params[key]})&`;
                params[key] = '';
              }
            }
          }

          if (filterQuery != "") {
            searchParams['@filter'] = filterQuery;
          }

          searchParams['@relationships'] = "UserInfo";
          const { Items, StatusCode } = await getTakeAwayUserAddressPageList(searchParams);
          return {
            data: Items[0]?.Records || [],
            success: StatusCode === 200,
            total: Items[0].Total,
          } as any;
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TakeAwayUserAddressPage;
